package com.zhou.cstm.web.servlet;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;


import com.zhou.cstm.domain.Customer;
import com.zhou.cstm.domain.PageBean;
import com.zhou.cstm.service.CustomerService;



@WebServlet("/CustomerServlet")
/**
 * web
 * @author jingbo
 *
 */
public class CustomerServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;
	private CustomerService customerService = new CustomerService();
    public CustomerServlet() {
        super();
    }
    /**
     * 
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    public String add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    	req.setCharacterEncoding("utf-8");
    	resp.setContentType("text/html;charset=utf-8");
    	Customer customer = new Customer();	
    	try {
    		String uuid = CommonUtils.uuid();
      		Map map = new HashMap(req.getParameterMap()); 
      		System.out.println(map.size());
  			System.out.println("11111111");
  			map.remove("method");
      		System.out.println(map.size());
			BeanUtils.populate(customer,map);
			customer.setCid(uuid);
			// 锟斤拷锟斤拷Service锟斤拷锟絘dd锟斤拷锟斤拷
			customerService.add(customer);
			req.setAttribute("customer", customer);
			return "forward:/msg.jsp"; 
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException();    
		}	
    }
    /**
     * 
     * @param req
     * @param resp
     * @return
     * @throws ServletException
     * @throws IOException
     */
//    public String findAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//		List customerList = customerService.findAll();
//		req.setAttribute("customerList", customerList);
//    	return "forward:/list.jsp"; 
//    }
    public String findAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		/*
		 * 传递页面的pageCode
		 * 给定页面 pageSize
		 * 使用pc和ps调用service方法，得到PageBean，保存到request域
		 * 转发到list.jsp
		 */
    	/*
    	 * 1、得到Pc,
    	 * 		如果参数pc不存在，则默认第一页，pc=1
    	 * 		
    	 */
    	int pc = getPc(req);
    	int ps = 10;
    	// 得到ps
        PageBean<Customer> pb = customerService.findAll(pc,ps); // 传递ps和pc给service,得到PageBean
        pb.setUrl(getURL(req));
        req.setAttribute("pb", pb);	//保存到request域
    	System.out.println(pb);
        return "forward:/list.jsp";
    }
    /**
     * 获取pc
     *
     */
    public int  getPc(HttpServletRequest req){
    	String value = req.getParameter("pc");
    	if(value == null || value.trim().isEmpty()){
    		return 1;
    	}
		return Integer.parseInt(value);
    }
    /**
     * 
     * @param req
     * @param resp
     * @return
     * @throws ServletException
     * @throws IOException
     */
    public String preEdit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String cid = req.getParameter("cid");
		if(cid == null || cid.trim().isEmpty()) return null;		
		Customer customer = customerService.load(cid);
		req.setAttribute("editCustomer", customer);
		System.out.println(customer);
		return "forward:/edit.jsp";
    }
    /**
     * 
     * @param req
     * @param resp
     * @return
     * @throws ServletException
     * @throws IOException
     */
    public String edit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    	Customer customer = new Customer();	
    	try {
      		Map map = new HashMap(req.getParameterMap()); 
  			map.remove("method");
      		
			BeanUtils.populate(customer,map);
			// 锟斤拷锟斤拷Service锟斤拷锟絘dd锟斤拷锟斤拷
			customerService.edit(customer);
			req.setAttribute("customer", customer);
			return "forward:/msg.jsp"; 
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException();    
		}	
    }
    /**
     * 
     * @param req
     * @param resp
     * @return
     * @throws ServletException
     * @throws IOException
     */
    public String delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {
    	String cid = req.getParameter("cid");
		if(cid == null || cid.trim().isEmpty()) return null;		
		customerService.delete(cid);
    	return "redirect:/CustomerServlet?method=findAll";
    }
    /**
     * 
     * @param req
     * @param resp
     * @return
     * @throws ServletException
     * @throws IOException
     */
    public String query(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
		// 把条件封装到customer对象
    	// 得到pc
    	// 给定ps
    	// 使用pc和ps以及条件对象调用service方法得到PageBean 
    	// 保存到request域
    	// 转发到list.jsp
    	
    	// 获取查询条件
    	// 处理get请求的编码问题，post已在父类BaseServlet处理
    		
    	Customer customer = new Customer();	
    	int pc = getPc(req);
    	int ps = 10;
    	try {
			Map map = new HashMap(req.getParameterMap()); 
			map.remove("method");
			BeanUtils.populate(customer,map);
			customer = encoding(customer);
			System.out.println(customer);
			PageBean<Customer> pb  = customerService.query(customer,pc,ps);	
			// url存导pb，其实是为了存储查询条件
			pb.setUrl(getURL(req));
			req.setAttribute("pb", pb);
			return "forward:/list.jsp"; 
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException();    
		}	

    }
    /**
     * 处理编码
     * @param customer
     * @return
     * @throws UnsupportedEncodingException 
     */
	private Customer encoding(Customer customer) throws UnsupportedEncodingException {
		String cname = customer.getCname();
		String gender = customer.getGender();
		String email = customer.getEmail();
		String cellphone = customer.getCellphone();
		System.out.println(customer);
		if(cname != null && !cname.trim().isEmpty()){
			cname = new String(cname.getBytes("UTF-8"),"UTF-8");
			customer.setCname(cname);
		}
		if(gender != null && !gender.trim().isEmpty()){
			gender = new String(gender.getBytes("UTF-8"),"UTF-8");
			System.out.println("gebder:" + gender);
			customer.setGender(gender);
		}
		if(email != null && !email.trim().isEmpty()){
			email = new String(email.getBytes("UTF-8"),"UTF-8");
			customer.setEmail(email);
		}
		if(cellphone != null && !cellphone.trim().isEmpty()){
			cellphone = new String(cellphone.getBytes("UTF-8"),"UTF-8");
			customer.setCellphone(cellphone);
		}
		return customer;
	}
//    public String query(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
//    {
//    	req.setCharacterEncoding("UTF-8");
//    	resp.setContentType("text/html;charset=utf-8");
//    	String username = req.getParameter("gender");
//    	 System.out.println("ssss:"+username);
//    	Customer customer = new Customer();	
//    	try {
//      		Map map = new HashMap(req.getParameterMap()); 
//      		map.remove("method");
//			BeanUtils.populate(customer,map);
//			List customerList  = customerService.query(customer);
//			System.out.println(customerList);
//			req.setAttribute("customerList", customerList);
//	    	return "forward:/list.jsp"; 
//    	} catch (Exception e) {
//			throw new RuntimeException();    
//		}	
//    }
    /**
     * 截取URL
     *  /项目名/Servlet路径?参数字符串
     * @return
     */
    public String getURL(HttpServletRequest req){
    	String contextPath = req.getContextPath();
    	String servletPath = req.getServletPath();
    	String queryString = req.getQueryString();
    	// 判断参数是否含有pc这个参数，如果包含，需要截取，pc由jsp页面指定
    	if(queryString.contains("pc")) {
    		int index = queryString.indexOf("pc");
    		queryString = queryString.substring(0,index);
    	}
    	return contextPath + servletPath + "?" +  queryString;
    }
    
}
